package com.example.demo;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableCircuitBreaker    // 使服务能够使用Hystrix和Ribbon库
@EnableEurekaClient     //告诉服务，他应该使用Eureka服务发现代理注册自身，并且服务调用是使用服务发现来查找远程服务的位置
@RestController
@RequestMapping("hello")
public class DemoApplication implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }


    @HystrixCommand(threadPoolKey = "helloThreadPool") // 包装器使用Hystrix断路器调用helloRemoteServiceCall方法
    public String helloRemoteServiceCall(String firstName, String lastName) {
        RestTemplate restTemplate = get();
        ResponseEntity<String> restExchange =
                restTemplate.exchange("http://logical-service-id/name/[ca]{firstName}/{lastName}",
                        HttpMethod.GET, null, String.class, firstName, lastName);
        return restExchange.getBody();

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public RestTemplate get() {
        return applicationContext.getBean(RestTemplate.class);
    }

    @RequestMapping(value = "/{firstName}/{lastName}", method = RequestMethod.GET)
    public String hello(@PathVariable("firstName") String firstName, @PathVariable("lastName") String lastName) {
        return helloRemoteServiceCall(firstName, lastName);
    }
}
